<?php

namespace App\Exceptions;

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use App\Services\ErrorMessageService;
use Throwable;

class Handler extends ExceptionHandler
{
    /**
     * The list of the inputs that are never flashed to the session on validation exceptions.
     *
     * @var array<int, string>
     */
    protected $dontFlash = [
        'current_password',
        'password',
        'password_confirmation',
    ];

    /**
     * Register the exception handling callbacks for the application.
     */
    public function register(): void
    {
        $this->reportable(function (Throwable $e) {
            // 记录所有异常到日志
            $this->logException($e);
        });
    }

    /**
     * Render an exception into an HTTP response.
     */
    public function render($request, Throwable $e)
    {
        // 如果是API请求，返回JSON格式错误
        if ($request->expectsJson()) {
            return $this->handleApiException($request, $e);
        }

        // 处理业务异常
        if ($e instanceof \App\Exceptions\BusinessException) {
            return $this->handleBusinessException($request, $e);
        }

        return parent::render($request, $e);
    }

    /**
     * 处理API异常
     */
    protected function handleApiException(Request $request, Throwable $e)
    {
        if ($e instanceof ValidationException) {
            $messages = ErrorMessageService::getValidationMessages($e);
            return response()->json([
                'success' => false,
                'message' => '数据验证失败',
                'errors' => $messages,
            ], 422);
        }

        if ($e instanceof HttpException) {
            return response()->json([
                'success' => false,
                'message' => ErrorMessageService::getFriendlyMessage($e),
            ], $e->getStatusCode());
        }

        $message = ErrorMessageService::getFriendlyMessage($e);
        
        return response()->json([
            'success' => false,
            'message' => $message,
        ], 500);
    }

    /**
     * 处理业务异常
     */
    protected function handleBusinessException(Request $request, \App\Exceptions\BusinessException $e)
    {
        $message = ErrorMessageService::getFriendlyMessage($e);
        
        if ($request->expectsJson()) {
            return response()->json([
                'success' => false,
                'message' => $message,
                'code' => $e->getCode(),
            ], $e->getStatusCode());
        }

        return redirect()->back()
            ->with('error', $message)
            ->withInput($request->except(['_token', 'password', 'password_confirmation']));
    }

    /**
     * 记录异常到日志
     */
    protected function logException(Throwable $e)
    {
        $context = [
            'exception' => get_class($e),
            'message' => $e->getMessage(),
            'file' => $e->getFile(),
            'line' => $e->getLine(),
            'trace' => $e->getTraceAsString(),
        ];

        // 添加请求上下文
        if (request()) {
            $context['request'] = [
                'url' => request()->fullUrl(),
                'method' => request()->method(),
                'ip' => request()->ip(),
                'user_agent' => request()->userAgent(),
                'user_id' => auth()->id(),
            ];
        }

        // 根据异常类型选择日志级别
        if ($e instanceof \App\Exceptions\BusinessException) {
            Log::warning('Business exception occurred', $context);
        } elseif ($e instanceof ValidationException) {
            Log::info('Validation exception occurred', $context);
        } else {
            Log::error('Unhandled exception occurred', $context);
        }
    }
}
